/*
* @Author: Administrator
* @Date:   2017-07-24 09:57:32
* @Last Modified by:   Administrator
* @Last Modified time: 2017-07-24 09:58:00
*/

'use strict';
const conf = {
    serverHost:'',
    imgHost:'http://img.jhmaimai.cn/'

}
class MM_comm {
    //请求服务器
    request(param){
        return new Promise((resolve,reject)=>{
            $.ajax({
                type:param.method||'get',
                url :param.url||"",
                dataType:param.type||'json',
                data:param.data||null,
                success : res=>{
                    if(res.status===0){
                        typeof resolve==="function"&&resolve(res.data);
                    }
                    else if(res.status===10){
                        this.doLogin();
                    }
                    else{
                        typeof reject==="function"&&reject(res.msg);
                    }
                },
                error : errorMsg=>{
                    typeof reject==="function"&&reject(errorMsg.status.text);
                }
            })
        }
    )}
    
    //获取请求服务器地址
    getServerHost(path){
        return conf.serverHost+path;
    }
    //获取图片地址
    getImgHost(path){
        return conf.imgHost+path;
    }
    //
    getImageUrl(img){
        return conf.imgHost+img;
    }
    // 获取url参数
    getUrlParam(name){
        var reg         = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"),
            queryString = window.location.hash.split('?')[1] || '',
            result      = queryString.match(reg);
        return result ? decodeURIComponent(result[2]) : null;
    }
    //处理本地储存
    setStorage(name,data){
        //储存数据为对象
        if(typeof data==='object'){
            let jsonString = JSON.stringify(data);
            window.localStorage.setItem(name,jsonString);
        }
        //数据为数字，字符串，布尔
        else if(typeof data === 'number' || typeof data === 'string' || typeof data === 'boolean'){
            window.localStorage.setItem(name, data);
        }
        // undefined / function
        else{
            alert('该数据类型不能用于本地存储');
        }
    }
    //获取本地储存
    getStorage(name){
        let data = window.localStorage.getItem(name);
        if(data){
            // JSON.parse
            return JSON.parse(data);
        }
        else{
            return '';
        }
    }
    //删除本地储存
    deleteStorage(name){
        window.localStorage.removeItem(name);
    }
    //登录
    doLogin(){
         window.location.href = '#/login?redirect=' + encodeURIComponent(window.location.hash);
    }
    //成功提示信息
    successTip(msg){
        alert(msg||'成功了');
    }
    //错误提示信息
    errorTip(msg){
        alert(msg||'失败了');
    }
}
export default MM_comm;